from fastapi import APIRouter, HTTPException
from datetime import datetime
from ..schemas.ceq import CEQRequest, CEQResponse
from ..core.tcp_client import send_xml_request
from ..core.xml_builder import build_request_xml, parse_response_xml
from ..config import settings
from ..core.logger import log_transaction

router = APIRouter()

@router.post("/ceq", response_model=CEQResponse)
async def query_balance(request: CEQRequest):
    try:
        # 准备请求数据
        now = datetime.now()
        request_data = {
            "trans_code": "CEQ",  # 交易类型
            "appid": request.appid,  # 交易来源
            "orderid": request.orderid,  # 使用前端传入的订单号
            "pan": request.pan,  # 卡号
            "trans_date": now.strftime("%Y%m%d"),  # 交易日期，格式：YYYYMMDD
            "trans_time": now.strftime("%H%M%S"),  # 交易时间，格式：HHMMSS
            "merno": settings.default_merno,  # 测试商户号
            "terminal": settings.default_terminal,  # 测试终端号
            "cur_code": "156"  # 人民币货币代码
        }
        
        # 构建XML报文
        request_xml = build_request_xml(request_data)
        
        # 发送请求并记录日志
        response_xml = await send_xml_request(request_xml)
        
        if not response_xml:
            raise HTTPException(status_code=500, detail="未收到服务器响应")
            
        # 解析响应
        response_data = parse_response_xml(response_xml)
        
        # 处理余额，确保是12位
        balance = response_data.get("balance", "0")
        balance = balance.zfill(12)  # 用0补齐到12位
        
        # 构建响应
        response = CEQResponse(
            resp_code=response_data.get("resp_code", "9999"),  # 响应码
            balance=balance,  # 账户余额，12位，单位分
            card_stat=response_data.get("card_stat", "00"),  # 卡片状态
            trans_sn=response_data.get("trans_sn", ""),  # 卡系统流水号
            error_msg="交易成功" if response_data.get("resp_code") == "0" else f"交易失败(响应码:{response_data.get('resp_code', '9999')})"
        )
        
        return response
        
    except HTTPException:
        raise
    except Exception as e:
        error_msg = str(e)
        log_transaction(
            trans_type="CEQ",
            direction="ERROR",
            message=error_msg,
            orderid=request.orderid,
            pan=request.pan
        )
        # 发生异常时返回错误响应
        return CEQResponse(
            resp_code="9999",
            balance="000000000000",
            card_stat="00",
            trans_sn="",
            error_msg=error_msg
        ) 